#include "P_NetAcceptAdapter.h"
#include "I_UnixNetProcessor.h"

extern EventProcessor eventProcessor;

NetAcceptAdapter::NetAcceptAdapter()
{
	loop = true;
	fd_blocking = false;
}

NetAcceptAdapter *
NetAcceptAdapter::clone()
{
	NetAcceptAdapter *na = new NetAcceptAdapter;
	*na = *this;
	return na;
}

void
NetAcceptAdapter::init_blocking_accept(const char *thread_name)
{
	SET_HANDLER(&NetAcceptAdapter::acceptLoopEvent);
	eventProcessor.spawn_thread(this, thread_name);
}

int
NetAcceptAdapter::acceptLoopEvent(int event, void *data)
{
	(void)event;
	(void)data;

	Connection conn;
	UnixNetVConnect *vc;
	int ret = -1;
	while(loop)
	{
		ret = server.accept(&conn, fd_blocking);
		if(_action.cancelled)
			break;

		if(ret == 0)
		{
			//EAGAIN or EWONDBLOCK
			continue;
		}else if(ret < 0)
		{
			//ERROR
			//debug_msg("the accept faild:errno is %d", -ret);
		}
		//accept success...
		vc = netProcessor.alloc_vc();
		vc->mutex = new_ProxyMutex();
		SET_CONTINUATION_HANDLER(vc, &UnixNetVConnect::acceptEvent);
		vc->fd = conn.fd;
		vc->conn = conn;
		vc->_action = _action.continuation;
		//schedule
		eventProcessor.schedule_imm(vc, ET_NET);
	}

	delete this;
}
